package de.mobizcorp.DWRESTServer.services

import grails.transaction.Transactional
import groovy.util.slurpersupport.NodeChild
import org.codehaus.groovy.grails.io.support.ClassPathResource
import dw.catalog.Catalog
import dw.catalog.Category

@Transactional
class DemandwareImporterService {
	String importFolder = new ClassPathResource("resources/imports/").getPath()
	Map resourceMap
	File siteExport
	XmlSlurper slurper = new XmlSlurper()
	
	/**
	 * Imports a Demandware site export.
	 * @param file The ZIP archive
	 */
	def importSiteExport(File file) {
		this.siteExport = file
		
		// Extract and validate the export. Build a resource map.
		extractExport()
		validateExport()
		parseExport()
		
		// Import catalogs and categories
		resourceMap["catalogs"]?.each {
			importCatalog(it)
			importCategories(it)
		}
		
	}
	
	/**
	 * Extracts a given site export ZIP into "importFolder/[archiveName]".
	 * After a successful extraction importFolder is set to this path.
	 */
	def extractExport() {
		
	}
	
	/**
	 * Validates if the currently set import folder contains a valid
	 * Demandware site export.
	 */
	def validateExport() {
		
	}
	
	/**
	 * Creates a map of importable files in the importFolder, making
	 * it accessible for further processing.
	 */
	def parseExport() {
		
	}
	
	/**
	 * Imports a Demandware catalog
	 * @param file Catalog file
	 */
    def importCatalog(File file) {
		def records = slurper.parse(file)
		
		// Save catalog
		Catalog catalog = new Catalog()
		catalog.ID = records.@"catalog-id".text()
		catalog.save()
		
		return null
    }
	
	/**
	 * Imports all the categories of a catalog
	 * @param file Catalog file
	 */
	def importCategories(File file) {
		def records = slurper.parse(file)
		Category category
		
		// Save categories		
		records."category".each {
			category = new Category()
			
			category.ID = 				parseXMLEntry(it.@"category-id")
			category.displayName = 		parseXMLEntry(it."display-name")
			category.description = 		parseXMLEntry(it."description")
			category.onlineFlag =		parseXMLEntry(it."onlineFlag")
			category.parent =			Category.find("FROM Category AS c WHERE c.ID = ?", it."parent".text())
			category.template =			parseXMLEntry(it."template")
			category.searchRank	=		parseXMLEntry(it."search-rank")
			
			category.custom =			[:]
			it."custom-attributes".each {
				category.custom.put(it.@"attribute-id".text(), it.text())
			}
			
			category.save()
		}
		
		return null
	}
	
	/**
	 * Parses an XML entry and returns its content with proper type.
	 * @param entry XML entry
	 * @return NULL or typed value
	 */
	private def parseXMLEntry(entry) {
		
		// NULL check
		if(!entry) {
			return null
		} else {
			entry = entry.text().toString()
		}
		
		// Empty check
		if(entry.isEmpty()) {
			return null
		}
		
		// Check type and return typed value
		if(entry.isFloat()) return Float.parseFloat(entry)
		if(entry.isInteger()) return Integer.parseInt(entry)
		return entry
	}
}
